package com.mbigger.admin.service.impl;

import com.google.common.collect.Lists;
import com.mbigger.admin.common.RequestHolder;
import com.mbigger.admin.dao.AclMapper;
import com.mbigger.admin.dao.RoleAclMapper;
import com.mbigger.admin.dao.RoleUserMapper;
import com.mbigger.admin.entity.Acl;
import com.mbigger.admin.entity.User;
import com.mbigger.admin.service.CoreService;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CoreServiceImpl implements CoreService{

	@Autowired
	private AclMapper aclMapper;
	@Autowired
	private RoleUserMapper roleUserMapper;
	@Autowired
	private RoleAclMapper roleAclMapper;
	
	public List<Acl> getCurrentUserAclList() {
		int userId = RequestHolder.getCurrentUser().getId();
		return getUserAclList(userId);
	}

	public List<Acl> getRoleAclList(int roleId) {
		List<Integer> aclIdList = roleAclMapper.getAclIdListByRoleIdList(Lists.<Integer>newArrayList(roleId));
		if (CollectionUtils.isEmpty(aclIdList)) {
			return Lists.newArrayList();
		}
		return aclMapper.getByIdList(aclIdList);
	}

	public List<Acl> getUserAclList(int userId) {
		if (isSuperAdmin()) {
			return aclMapper.getAll();
		}
		List<Integer> userRoleIdList = roleUserMapper.getRoleIdListByUserId(userId);
		if (CollectionUtils.isEmpty(userRoleIdList)) {
			return Lists.newArrayList();
		}
		List<Integer> userAclIdList = roleAclMapper.getAclIdListByRoleIdList(userRoleIdList);
		if (CollectionUtils.isEmpty(userAclIdList)) {
			return Lists.newArrayList();
		}
		return aclMapper.getByIdList(userAclIdList);
	}

	public boolean isSuperAdmin() {
		// 这里是我自己定义了一个假的超级管理员规则，实际中要根据项目进行修改
		// 可以是配置文件获取，可以指定某个用户，也可以指定某个角色
		User user = RequestHolder.getCurrentUser();
		if (user.getMail().contains("admin")) {
			return true;
		}
		return false;
	}

}
